<?php
// +----------------------------------------------------------------------
// | MubinAdmin
// +----------------------------------------------------------------------
// | 版权所有 2015~2020 泉州市牧滨电子商务有限公司 [ http://www.mubin.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.mubin.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/mubin/MubinAdmin
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\common\traits\BaseService;
use app\admin\logic\AdminUserLogic;
use app\common\facade\UserInfo;
use think\facade\{Config,Cookie,Request};

class AdminUserService
{
	use BaseService;

	public function __construct()
	{
		$this->logic = new AdminUserLogic();
	}

    /**
     * 登录
     * @param array|null $param
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(?array $param = [])
    {
        $type=$this->analysisUsername($param['username']);
        $userId= $this->logic->userLogin($param['username'], $param['password'], $type);
        $userInfo = $this->logic->userInfo($userId);
        if ($userId === false) {
            return $this->error($this->logic->getError());
        }
        //处理用户登录信息
        UserInfo::autoLogin($userInfo->toArray());
        $this->remember($param['username']); //记住我
        return $userId;
    }
    
    /**
     * 分析用户名类型
     * @author staitc7 <static7@qq.com>
     * @param null|string $username
     * @return mixed
     */
    public function analysisUsername(?string $username=null)
    {
        //手机号
        if (preg_match('/0?(13|14|15|17|18|19)[0-9]{9}/', $username)){
            return 3;
        }
        //邮箱
        if (preg_match('/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/', $username)){
            return 2;
        }
        //用户名
        if (preg_match('/[A-Za-z0-9_]+/', $username)){
            return 1;
        }
        return null;
    }

    /**
     * 记住我
     * @author staitc7 <static7@qq.com>
     * @param null|string $username
     * @return mixed
     */
    public function remember(?string $username='')
    {
        $remember=Request::param('remember') ?? 0;
        if ((int)$remember ===1){
            Cookie::forever('remember',$username);
        }else{
            Cookie::delete('remember');
        }
        return true;
    }
}